<?php
namespace App\Logic\apiLogin;

use App\Server\ApiService;
use App\Service\JwtService;
use Illuminate\Support\Facades\Cache;

class login
{
    /**
     * fw
     * 逻辑层封装发短信
     * @param $phone
     * @return string
     */
    static function sendSms($phone){
        $rand=mt_rand(1000,9999);
        Cache::put('code'.$rand,$rand);
        $statusStr = array(
            "0" => "短信发送成功",
            "-1" => "参数不全",
            "-2" => "服务器空间不支持,请确认支持curl或者fsocket，联系您的空间商解决或者更换空间！",
            "30" => "密码错误",
            "40" => "账号不存在",
            "41" => "余额不足",
            "42" => "帐户已过期",
            "43" => "IP地址限制",
            "50" => "内容含有敏感词"
        );
        $smsapi = "http://api.smsbao.com/";
        $user = "gaojiajing"; //短信平台帐号
        $pass = md5("340c801f4a8f497c9eee1c41a75547ed"); //短信平台密码
        $content="『 欢饮光临伟盛集团 』：您的验证码为：".$rand;//要发送的短信内容
        $sendurl = $smsapi."sms?u=".$user."&p=".$pass."&m=".$phone."&c=".urlencode($content);
        $result =file_get_contents($sendurl) ;
        if($result==0)
        {
            return $statusStr[$result].':'.$rand;
        }
        return $statusStr[$result];
    }
    /**
     * fw
     * 小程序登陆验证
     * @param $code
     * @param $phone
     * @return string
     */
    static function check($code,$phone){
        $trueCode=Cache::get('code'.$code);
        $truePhone=Cache::get('phone'.$phone);
        if($truePhone==null)
        {
            return '与发送短信的手机号不一致';
        }
        if($code!=$trueCode||$trueCode==null)
        {
            return '验证码输入错误，请重试';
        }

        $people=\App\Models\Login::where('phone',$phone)->first();

        $token=JwtService::encode($phone);
        if(!$people)
        {
            \App\Models\Login::create([
                'username'=>'root',
                'phone'=>$phone,
                'status'=>1,
                'role_id'=>1,
                'token'=>$token,
            ]);
            return $token;
        }

        return $token;
    }
    /**
     * fw
     * 请求微信官方小程序登录接口
     * @param $nickName
     * @param $code
     * @return string
     */
    static function empower($nickName,$code){
        $appid="wxc4ad2cd3f7241dd5";
        $secret="0a0f038ba0e272fcdd1dede5a172afbf";
        $sql="https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";
        $sql=json_decode(file_get_contents($sql),true);

        $people=\App\Models\Login::where('openid',$sql['openid'])->first();

        $token=JwtService::encode($sql['openid']);
        if(!$people)
        {
            \App\Models\Login::create([
                'username'=>$nickName,
                'status'=>1,
                'session_key'=>$sql['session_key'],
                'openid'=>$sql['openid'],
                'role_id'=>1,
                'token'=>$token
            ]);
            return $token;
        }
        return $token;
    }
}
